#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

#include "nweb.h"
#include "nweb_log.h"
#include "mime.h"

/* Request Analyzer */
void analyze_request(request_rec* r) {
    int i, j, len;
    
    if (strncmp(r->method, "GET", 3) && strncmp(r->method, "get", 3))
        nweb_log(SORRY, "Only simple GET operation supported", r->buffer, r->fd);
    // TODO maybe exit in here?

    int urilen = strlen(r->unparsed_uri);

    for (j = 0; j < urilen; j++) /* check for illegal parent directory use .. */
        if (r->unparsed_uri[j] == '.' && r->unparsed_uri[j + 1] == '.')
            nweb_log(SORRY, "Parent directory (..) path names not supported", r->buffer, r->fd);

    // TODO check if it is GET
    if (!strncmp(r->unparsed_uri, "/\0", 2)) {/* convert no filename to index file */
        r->uri = "/index.html"; /* default file if no file specify */
    } else {
        r->uri = r->unparsed_uri;
    }

    /* work out the file type and check we support it */
    urilen = strlen(r->uri);
    r->fstr = (char *) 0;
    for (i = 0; extensions[i].ext != 0; i++) {
        len = strlen(extensions[i].ext);
        char *ext = &r->uri[urilen - len];
        if (!strncmp(ext, extensions[i].ext, len)) {
            r->fstr = extensions[i].filetype;
            break;
        }
    }
    if (r->fstr == 0) nweb_log(SORRY, "file extension type not supported", r->buffer, r->fd);
}

void request_rec_destroy(request_rec *r) {
	free(r->buffer);
	free(r);
}

